package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpRequestUtil {

	public static void returnFile(HttpServletRequest request,
			HttpServletResponse response, ServletContext sc, String filePath,
			String fileName) throws FileNotFoundException, IOException {

		// Get the MIME type of the image
		String mimeType = sc.getMimeType(filePath);

		// if (mimeType == null) {
		// sc.log("Could not get MIME type of " + filePath);
		// response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		// return;
		// }

		if (mimeType != null) {
			// Set content type
			response.setContentType(mimeType);
			// response.setC
		} else {
			response.setContentType("application/octet-stream");
		}

		// Set content size
		File file = new File(filePath);
		response.setContentLength((int) file.length());
		response.setHeader("content-disposition", "attachment; filename=\""
				+ fileName + "\"");

		// Open the file and output streams
		FileInputStream in = new FileInputStream(file);
		OutputStream out = response.getOutputStream();

		// Copy the contents of the file to the output stream
		byte[] buf = new byte[1024];
		int count = 0;
		while ((count = in.read(buf)) >= 0) {
			out.write(buf, 0, count);
		}
		in.close();
		out.close();
	}

}
